import React, { useState } from 'react'
import ReactDOM from 'react-dom/client'
import styled, { keyframes } from 'styled-components'
import { pxToVw } from './utils'
const fadeInOut = keyframes`
  0% { opacity: 0; transform: translateY(20px); }
  10% { opacity: 1; transform: translateY(0); }
  90% { opacity: 1; transform: translateY(0); }
  100% { opacity: 0; transform: translateY(20px); }
`

export const TOAST_TYPES = {
  SUCCESS: 'success',
  INFO: 'info',
  ERROR: 'error',
}

const StyledToastContainer = styled.div`
  position: fixed;
  top: 20px;
  left: 50%;
  width:300px;
  transform: translateX(-50%);
  z-index: 9999;
  display: flex;
  flex-direction: column;
  align-items: center;
  pointer-events: none; /* 避免遮挡下方元素 */
`
const StyledToastItem = styled.div`
  padding: ${pxToVw(12)} ${pxToVw(24)};
  margin-bottom: 8px;
  border-radius: 8px;
  color: white;
  font-size: ${pxToVw(24)};
  animation: ${fadeInOut} 3s ease-in-out forwards;
  width: 80%;
  text-align: center;
  pointer-events: auto; /* 允许点击（可选） */

  ${({ type }) => {
    switch (type) {
      case TOAST_TYPES.SUCCESS:
        return 'background: #28a745;'
      case TOAST_TYPES.ERROR:
        return 'background: #dc3545;'
      default:
        return 'background: #17a2b8;'
    }
  }}
`

let toastList = []
let toastRoot = null

export const initGlobalToast = () => {
  if (!toastRoot) {
    const container = document.createElement('div')
    document.body.appendChild(container)
    toastRoot = ReactDOM.createRoot(container)
    toastRoot.render(<StyledToastContainer />)
  }
}

const updateToastList = (newList) => {
  console.log('newList', newList)
  toastList = newList
  if (toastRoot) {
    toastRoot.render(
      <StyledToastContainer>
        {toastList.map((toast) => {
          return (
            <StyledToastItem key={toast.id} type={toast.type} duration={toast.duration}>
              {toast.message}
            </StyledToastItem>
          )
        })}
      </StyledToastContainer>
    )
  }
}

export const toast = (message, type = TOAST_TYPES.INFO, duration = 3000) => {
  const id = Date.now()
  const newToast = {
    id,
    message,
    type,
    duration,
  }
  updateToastList([...toastList, newToast])
  setTimeout(() => {
    updateToastList(toastList.filter((e) => e.id !== id))
  }, duration)
}
